import * as c from '@/services/consts';
import * as apiGroup from '@/services/vpnGroup';
import * as api from '@/services/vpnServer';
import * as utils from '@/utils/utils';
import {
  CheckCircleFilled,
  CloseCircleFilled,
  CloudServerOutlined,
  ExclamationCircleFilled,
  PlusOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { PageContainer, ProList, TableDropdown } from '@ant-design/pro-components';
import type {
  ActionType,
  ColumnsState,
  ProColumns,
} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Badge,
  Button,
  Popconfirm,
  Space,
  Tag,
  Tooltip,
  TreeSelect,
  message,
} from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import VpnServerBatchRemoveForm from './components/BatchRemoveForm';
import VpnServerBatchForm from './components/BatchVpnServerForm';
import VpnServerExportIpForm from './components/VpnServerExportIpForm';
import VpnServerForm from './components/VpnServerForm';
import SyncIpForm from './components/SyncIpForm';
import VpnServerExportYamlForm from './components/VpnServerExportYamlForm';
import BatchChangeForm from './components/BatchChangeForm';
import DeployForm from '../Deploy/DeployForm';
import * as apiDeploy from '@/services/deploy';
import dayjs from 'dayjs';
import { DeployLogStatusTag } from '@/components/StatusTag';

const VpnServerList: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.VpnServer | undefined>(undefined);
  const [formBatchVisible, setFormBatchVisible] = useState<boolean>(false);
  const [formBatchRemoveVisible, setFormBatchRemoveVisible] = useState<boolean>(false);
  const [formExportIpVisible, setFormExportIpVisible] = useState<boolean>(false);
  const [formExportYamlVisible, setFormExportYamlVisible] = useState<boolean>(false);
  const [groupTreeData, setGroupTreeData] = useState<API.TreeSelectItem[] | undefined>(undefined);
  const [formBatchChangeVisible, setFormBatchChangeVisible] = useState<boolean>(false);
  const [productId, setProductId] = useState<string | undefined>(undefined);
  const [groupIds, setGroupIds] = useState<string[] | undefined>(undefined);
  const [totalUserCount, setTotalUserCount] = useState<number>(0);
  const [totalValidServerCount, setTotalValidServerCount] = useState<number | undefined>(0);
  const [totalServerCount, setTotalServerCount] = useState<number | undefined>(0);
  const [selectIds, setSelectIds] = useState<any[]>([]);
  const [columnsStateMap, setColumnsStateMap] = useState<Record<string, ColumnsState>>({});
  const [formSyncIpVisible, setFormSyncIpVisible] = useState<boolean>(false);
  const [formDeployVisible, setFormDeployVisible] = useState<boolean>(false);
  const [selectServer, setSelectServer] = useState<API.VpnServerMonitorModel[] | undefined>(undefined);
  
  const actionRef = useRef<ActionType>();
  const { hasRight } = useModel('useAuthModel');

  const {
    getProductMenuItems,
    getSupplier,
    supplierOptions,
    getGroupAreaFilterPolicyText,
    getVpnGroupExTrees,
    setDeployConfigPublish,
  } = useModel('useGlobalModel', (model) => ({
    getProductMenuItems: model.getProductMenuItems,
    getSupplier: model.getSupplier,
    supplierOptions: model.supplierOptions,
    getGroupAreaFilterPolicyText: model.getGroupAreaFilterPolicyText,
    getVpnGroupExTrees: model.getVpnGroupExTrees,
    setDeployConfigPublish: model.setDeployConfigPublish,
  }));

  const productMenuItems = getProductMenuItems(true);

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const treeData = getVpnGroupExTrees(productId);
    if (treeData && treeData.length > 0) {
      setGroupTreeData(treeData);
    } else {
      setGroupTreeData(undefined);
      setGroupIds(undefined);
    }

    const result = await api.list(params, undefined, filter);
    if (result.success) {
      setTotalUserCount(result.totalUserCount);
      setTotalServerCount(result.data.length);
      setTotalValidServerCount(result.totalValidServerCount);
    }

    return Promise.resolve(result);
  };

  // const handleFormSubmit = async (record: API.VpnServer) => {
  //   let result: API.Result;
  //   if (current) {
  //     result = await api.update({
  //       ...current,
  //       ...record,
  //     });
  //   } else {
  //     result = await api.add({ ...record });
  //   }
  //   if (result && result.success === true) {
  //     setCurrent(undefined);
  //     setFormVisible(false);
  //     actionRef.current?.reload();
  //   }
  // };

  const handleRemove = async (id: string) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  const handleFormBatchSubmit = async (record: API.VpnServer[]) => {
    let result: API.Result;
    result = await api.adds({ data: record });

    if (result && result.success === true) {
      setDeployConfigPublish(true);
      setFormBatchVisible(false);
      actionRef.current?.reload();
    }
  };

  const handleRemoveList = async () => {
    if (selectIds.length < 1) return;
    const result = await api.removes({ keys: selectIds });
    if (result && result.success === true) {
      //onCleanSelected();
      setSelectIds([]);
      actionRef.current?.clearSelected?.();
      actionRef.current?.reload();
    }
  };

  const handleFormBatchRemoveSubmit = async (insts: number[]) => {
    let result: API.Result;
    result = await api.removeInsts({ keys: insts });

    if (result && result.success === true) {
      setFormBatchRemoveVisible(false);
      actionRef.current?.reload();
    }
  };  

  const handlePublishConfig = async (isAll:boolean, must: boolean) => {
    message.info('配置下发中');
    if(isAll == true){
      const result = await apiDeploy.publishConfig({ keys : undefined, must: must });
      if (result && result.success === true) {
        setDeployConfigPublish(false);
        message.success('配置下发成功');
        actionRef.current?.reload();
        return;
      }
      else{
        message.error('配置下发请求失败');
      }
    }
    else{
      if(!selectIds || selectIds.length < 1){
        message.error('请选把要下发配置的节点');
        return;
      }
      const result = await apiDeploy.publishConfig({ keys: selectIds, must: must });
      if (result && result.success === true) {
        setDeployConfigPublish(false);
        setSelectIds([]);
        actionRef.current?.clearSelected?.();
        actionRef.current?.reload();
      }
      else{
        message.error('配置下发请求失败');
      }
    }
  };

  const handleRecover = async () => {
    if (selectIds.length < 1) return;
    const result = await apiDeploy.recover({ keys: selectIds });
    if (result && result.success === true) {
      //onCleanSelected();
      setSelectIds([]);
      actionRef.current?.clearSelected?.();
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.VpnServerMonitorModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: (a, b) => (a.status == true ? 1 : 0) - (b.status == true ? 1 : 0),
      search: false,
      // valueEnum: {
      //   true: { status: 'Success' },
      //   false: { status: 'Error' },
      // },
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
      filters: [
        { text: '启用', value: true },
        { text: '禁用', value: false },
      ],
    },
    {
      title: '实例ID',
      // align: 'center',
      width: 85,
      dataIndex: 'instanceId',
      sorter: (a, b) => a.instanceId - b.instanceId,
      render: (_, record) => {
        return record.unscheduled == true ? <Tag color='gold'>{record.instanceId}</Tag> : record.instanceId;
      },
    },
    // {
    //   title: '地区',
    //   dataIndex: 'location',
    //   width: 80,
    //   sorter: (a, b) => (a.location ?? '').localeCompare(b.location ?? ''),
    // },
    {
      title: '类型',
      // align: 'center',
      width: 70,
      dataIndex: 'serverType',
      sorter: (a, b) => (a.serverType ?? 0) - (b.serverType ?? 0),
      hideInSearch: true,
      render: (_, record) => {
        return c.getServerType(record.serverType)?.label;
      },
      // filters: c.ServerTypes,
    },
    {
      title: '供应商',
      // align: 'center',
      width: 100,
      dataIndex: 'supplierId',
      sorter: (a, b) => (a.supplierId ?? 0) - (b.supplierId ?? 0),
      hideInSearch: true,
      render: (_, record) => {
        return getSupplier(record.supplierId)?.name;
      },
    },
    // {
    //   title: '供应地区',
    //   align: 'center',
    //   width: 100,
    //   dataIndex: 'supplyAreaId',
    //   sorter: (a, b) => (a.supplyAreaId ?? 0) - (b.supplyAreaId ?? 0),
    //   hideInSearch: true,
    //   render: (_, record) => {
    //     return getSupplyArea(record.supplyAreaId)?.name;
    //   },
    // },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
      render: (_, record) => {
        return <>
        <div>{record.name}</div>        
            <DeployLogStatusTag log={record.serverInfo?.deployLog} />
        </>
      }
    },
    {
      title: '服务器标识',
      dataIndex: 'serverName',
      sorter: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
      render: (_, record) => {
        return <>
        <div>{record.serverInfo?.serverName}</div>        
        {record.serverInfo?.serverRegion ? <div><Tag color='blue'>{record.serverInfo?.serverRegion}</Tag></div> : ''}
        </>
      }
    },
    {
      title: '类型',
      dataIndex: 'serverType',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        allowClear: true,
        options: c.ServerTypes,
      },
    },
    {
      title: '供应商',
      dataIndex: 'supplierId',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        mode: 'multiple',
        allowClear: true,
        options: supplierOptions,
      },
    },
    // {
    //   title: '供应地区',
    //   dataIndex: 'supplyAreaId',
    //   hideInTable: true,
    //   valueType: 'select',
    //   fieldProps: {
    //     mode: 'multiple',
    //     allowClear: true,
    //     options: supplyAreaOptions,
    //   },
    // },
    {
      title: '分组',
      dataIndex: 'memberLevel',
      search: false,
      // width:250,
      render: (_, record) => {
        if (!record.groups) {
          return <></>;
        }
        return record.groups.map((item) => (
          <Space>
            <Tooltip
              key={`group_${item.id}`}
              title={apiGroup.getGroupTagTitle(item)}
            >
              <Tag
                key={`group_${item.id}`}
                color={
                  item.type == c.VpnGroupType.Ghost.value ? 'green' : 'blue'
                }
              >
                {apiGroup.getGroupTagTitle(item)}
              </Tag>
              {/* {item.protocol ? <Tag color={item.protocol == 3 ? 'green' : item.protocol == 1 ? "blue" : item.protocol == 2 ? "purple" : ""}>{c.getObjectText(c.VpnGroupProtocols, item.protocol)}</Tag> : ""} */}
              {item.protocol ? (
                <Tag color="blue">
                  {c.getObjectText(c.VpnGroupProtocols, item.protocol)}
                </Tag>
              ) : (
                ''
              )}
              {item.policy && item.policy.displayAreaFilterPolicy ? (
                <Tag color="green">
                  {getGroupAreaFilterPolicyText(item.policy)}
                </Tag>
              ) : (
                ''
              )}

            {item.changeIp > 0 ? (
              <Tooltip key={`ip_${item.id}`} title="自动切换IP">
                <Tag key={`ip_${item.id}`} color="orange">
                  {item.changeIp}分钟
                </Tag>
              </Tooltip>
            ) : (
              ''
            )}

            </Tooltip>
          </Space>
        ));
      },
      filters: [
        { text: c.MemberLevel.Trial.label, value: c.MemberLevel.Trial.value },
        { text: c.MemberLevel.Free.label, value: c.MemberLevel.Free.value },
        { text: c.MemberLevel.VIP.label, value: c.MemberLevel.VIP.value },
        {
          text: c.MemberLevel.Internal.label,
          value: c.MemberLevel.Internal.value,
        },
      ],
    },
    {
      title: 'IP',
      dataIndex: 'ip',
      width: 120,
      sorter: (a, b) => (a.ip ?? '').localeCompare(b.ip ?? ''),
    },
    {
      title: '端口',
      align: 'center',
      dataIndex: 'port',
      search: false,
      width: 60,
      sorter: (a, b) => (a.port ?? 0) - (b.port ?? 0),
    },
    {
      title: '测速端口',
      align: 'center',
      dataIndex: 'pingPort',
      search: false,
      width: 90,
      sorter: (a, b) => (a.pingPort ?? 0) - (b.pingPort ?? 0),
    },
    {
      title: '分组类型',
      dataIndex: 'groupType',
      width: 150,
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        // mode: 'multiple',
        allowClear: true,
        options: c.VpnGroupTypeOptions,
      },
    },
    {
      title: '用户等级',
      dataIndex: 'groupMemberLevel',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        // mode: 'multiple',
        allowClear: true,
        options: c.MemberLevelOptions,
      },
    },
    {
      title: '网络配置',
      dataIndex: 'netConfig',
      width: 150,
      search: false,
      render: (_, record) => {
        if (!record.netConfig) {
          return <></>;
        }
        // return (<div style={{overflowY:'scroll', maxHeight:300, maxWidth:200}}>
        // {record.netConfig.map((item) => (
        //   <Space>
        //     <Tooltip key={item.id} title={item.remark}>
        //       <Tag key={item.id} color={item.status ? 'blue' : 'gray'}>
        //         {item.ip}
        //         {item.outIp !== undefined &&
        //           item.outIp != '' &&
        //           `/${item.outIp}`}
        //       </Tag>
        //     </Tooltip>
        //   </Space>
        // ))
        // }
        //   </div>);
        
        return record.netConfig && record.netConfig.length > 0 ? <ProList
        rowKey="id"
        ghost={true}
        dataSource={[{title:'IP', description:''}]}
        key="keyNotePlat"
        id="keyNotePlat"
        metas={{
          title: {
            render: (text, record2) => (
              <div>IP数量: {record.netConfig?.length}</div>
            ),
          },
          description: {
            render: (text, record2) => (
              record.netConfig.map((item) => (
              <Space>
                <Tooltip key={item.id} title={item.remark}>
                  <Tag key={item.id} color={item.status ? item.blocked == true ? 'error' : 'blue' : 'gray'} style={{fontWeight: item.relay ? 'bold' : 'normal'}}>
                    {item.ip}
                    {item.outIp !== undefined &&
                      item.outIp != '' &&
                      `/${item.outIp}`}
                  </Tag>
                </Tooltip>
              </Space>
            ))
            ),
            fieldProps: {},
          },
        }}
        expandable={{
          // expandedRowKeys,
          // expandRowByClick:true,
          defaultExpandAllRows: false,
          // onExpandedRowsChange: (expandedKeys) => {
          //   setExpandedRowKeys(expandedKeys);
          // },
        }}
      />
      : ''
      },
    },
    {
      title: '在线',
      align: 'center',
      width: 80,
      dataIndex: 'online',
      sorter: (a, b) => (a.online ? 1 : 0) - (b.online ? 1 : 0),
      search: false,
      // valueEnum: {
      //   true: { status: 'Success' },
      //   false: { status: 'Error' },
      // },
      render: (_, record) => {
        return (
          <>
            {record.online ? (
              <Badge
                count={<CheckCircleFilled style={{ color: '#52c41a' }} />}
              />
            ) : (
              <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
            )}
            {record.online == false && record.updateTime ? (
              <div>{utils.formatUtcToLocal(record.updateTime)}</div>
            ) : (
              ''
            )}
          </>
        );
      },
      filters: [
        { text: '在线', value: 1 },
        { text: '离线', value: 2 },
      ],
    },
    {
      title: 'Helper',
      align: 'center',
      width: 70,
      dataIndex: 'helperOnline',
      sorter: (a, b) => (a.helperOnline == true ? 1 : 0) - (b.helperOnline == true ? 1 : 0),
      render: (_, record) => {
        return (
          <>
            {record.helperOnline == true ? (
              <Badge
                count={<CheckCircleFilled style={{ color: '#52c41a' }} />}
              />
            ) : record.helperOnline == false ? (
              <Badge count={<ExclamationCircleFilled style={{ color: 'orange' }} />} />
            ):''}
            {record.helperOnline == false && record.helperOnlineTime ? (
              <div>{utils.formatDate(record.helperOnlineTime)}</div>
            ) : (
              ''
            )}
          </>
        );
      },
    },
    {
      title: '版本',
      // align: 'center',
      width: 60,
      sorter: (a, b) => (a.version ?? '').localeCompare(b.version ?? ''),
      search: false,
      dataIndex: 'version',
    },
    {
      title: '启动时间',
      // align: 'center',
      dataIndex: 'startTime',
      sorter: (a, b) =>
        utils
          .formatUtcToLocal(a.startTime)
          .localeCompare(utils.formatUtcToLocal(b.startTime)),
      search: false,
      width: 90,
      render: (_, record) => utils.formatUtcToLocal(record.startTime),
    },
    // {
    //   title: '运行时长',
    //   // align: 'center',
    //   dataIndex: 'runSeconds',
    //   sorter: (a, b) => (a.runSeconds ?? 0) - (b.runSeconds ?? 0),
    //   search: false,
    //   width: 90,
    //   render: (_, record) =>
    //     record.runSeconds > 0 ? utils.formatDuration(record.runSeconds) : '',
    // },
    {
      title: '在线用户',
      dataIndex: 'userCount',
      // align: 'center',
      sorter: (a, b) => (a.userCount ?? 0) - (b.userCount ?? 0),
      search: false,
      width: 90,
    },
    // {
    //   title: '用户',
    //   align: 'center',
    //   width: 80,
    //   dataIndex: 'userCount',
    // },
    // {
    //   title: '流量',
    //   align: 'center',
    //   width: 120,
    //   dataIndex: 'upload',
    //   render: (_, record) => utils.formatDataSize(record.upload),
    // },
    // {
    //   title: '用户限制',
    //   align: 'center',
    //   width: 80,
    //   dataIndex: 'maxUser',
    //   render: (val) => ((val as number) > 0 ? val : 'N/A'),
    // },
    {
      title: '带宽限制',
      // align: 'center',
      dataIndex: 'maxBandwidth',
      sorter: (a, b) => (a.maxBandwidth ?? 0) - (b.maxBandwidth ?? 0),
      search: false,
      width: 90,
      render: (text) => ((text as number) > 0 ? text : ''),
    },
    {
      title: '上架',
      // align: 'center',
      dataIndex: 'addedDate',
      valueType: 'date',
      sorter: (a, b) => dayjs(a.addedDate).format('YYYY-MM-DD HH:mm:ss').localeCompare(dayjs(b.addedDate).format('YYYY-MM-DD HH:mm:ss')),
      width: 90,
      render: (_, record) => {
        return <>
        {record.addedDate ? <div>{dayjs(record.addedDate).format('YYYY-MM-DD')}</div> : ''}
        {record.createUser ? <div>{record.createUser}</div> : ''}
        </>
      }
    },
    // {
    //   title: '上架人',
    //   dataIndex: 'createUser',
    //   search: false,
    //   width: 90,
    // },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
      // search: false,
    },
    {
      title: '配置IP',
      dataIndex: 'bindIp',
      hideInTable: true,
    },
    {
      title: '配置IP备注',
      dataIndex: 'bindIpRemark',
      hideInTable: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      render: (_, record) => {
        let cmps = [];

        if (hasRight('vpnserver_update')) {
          cmps.push(
            <a
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        

        if (hasRight('deploy_create')){
          cmps.push(
            <a
              onClick={async () => {
                setFormDeployVisible(true);
                setSelectServer([record]);
              }}
            >
              部署
            </a>
          );
        }

        if (hasRight('vpnserver_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        search={{
          labelWidth: 80,
          defaultCollapsed: false,
          span: 4,
        }}
        options={{
          fullScreen: false,
          reload: true,
          //setting: false,
          density: false,
          setting: {
            listsHeight: 600,
          },
        }}
        pagination={{
          defaultPageSize: 100,
          pageSizeOptions: [
            '100',
            '200',
            '300',
            '500',
            '1000',
            // '2000',
            // '5000',
            // '10000',
          ],
          hideOnSinglePage: false,
          // current: pageCurrent,
          // total: totalCount,
        }}
        // pagination={false}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}
        toolbar={{
          // filter: (
          //   <>
          //     <Space
          //       style={{
          //         marginRight: '10px',
          //       }}
          //     >
          //       <span>
          //         在线用户合计：<Tag color="#87d068">{totalConnCount}</Tag>
          //       </span>
          //     </Space>
          //     <Space>
          //       <TreeSelect
          //         style={{ minWidth: '180px' }}
          //         dropdownMatchSelectWidth={false}
          //         placeholder="选择分组过滤"
          //         allowClear={true}
          //         showSearch={false}
          //         treeCheckable={true}
          //         // multiple={false}
          //         treeDefaultExpandAll
          //         treeData={groupTreeData}
          //         value={groupIds}
          //         onChange={(value) => {
          //           // setGroupId(value ? value : undefined);
          //           setGroupIds(value ? value : undefined);
          //         }}
          //       />
          //     </Space>
          //   </>
          //   // <LightFilter>
          //   //   <Form.Item name="groupIds" label="分组">
          //   //     <TreeSelect
          //   //       treeData={groupTreeData}
          //   //       placeholder="Please select"
          //   //       treeDefaultExpandAll
          //   //       onChange={(value) => {
          //   //         setGroupId(value ? value : '');
          //   //       }}
          //   //     />
          //   //   </Form.Item>
          //   // </LightFilter>
          // ),
          multipleLine: true,
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              //console.log('tabKey', tabKey);
              setProductId(tabKey as string);

              // actionRef.current?.reset();
            },
          },
          // tabs: {
          //   activeKey: productId,
          //   items: [
          //     {
          //       tab: '全部',
          //       key: '',
          //     },
          //   ],
          //   onChange: (tabKey) => {
          //     //console.log('tabKey', tabKey);
          //     setProductId(tabKey as string);

          //     // actionRef.current?.reset();
          //   },
          // },
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];
          // toolbarDoms.push(
          //   <Space>
          //     <b>在线</b>
          //     <Radio.Group defaultValue="a" buttonStyle="solid">
          //       <Radio.Button
          //         value="a"
          //         onClick={() => {
          //           setFilterOnline(undefined);
          //         }}
          //       >
          //         全部
          //       </Radio.Button>
          //       <Radio.Button
          //         value="b"
          //         onClick={() => {
          //           setFilterOnline(1);
          //         }}
          //       >
          //         在线
          //       </Radio.Button>
          //       <Radio.Button
          //         value="c"
          //         onClick={() => {
          //           setFilterOnline(2);
          //         }}
          //       >
          //         离线
          //       </Radio.Button>
          //     </Radio.Group>
          //   </Space>,
          // );

          // toolbarDoms.push(
          //   <Space>
          //     <b>类型</b>
          //     <Radio.Group defaultValue="a" buttonStyle="solid">
          //       <Radio.Button
          //         value="a"
          //         onClick={() => {
          //           setFilterServerType(undefined);
          //         }}
          //       >
          //         全部
          //       </Radio.Button>
          //       <Radio.Button
          //         value="b"
          //         onClick={() => {
          //           setFilterServerType(1);
          //         }}
          //       >
          //         物理机
          //       </Radio.Button>
          //       <Radio.Button
          //         value="c"
          //         onClick={() => {
          //           setFilterServerType(2);
          //         }}
          //       >
          //         虚拟机
          //       </Radio.Button>
          //     </Radio.Group>
          //   </Space>,
          // );

          // toolbarDoms.push(
          //   <Space>
          //     <b>状态</b>
          //     <Radio.Group defaultValue="a" buttonStyle="solid">
          //       <Radio.Button
          //         value="a"
          //         onClick={() => {
          //           setFilterServerStatus(undefined);
          //         }}
          //       >
          //         全部
          //       </Radio.Button>
          //       <Radio.Button
          //         value="b"
          //         onClick={() => {
          //           setFilterServerStatus(true);
          //         }}
          //       >
          //         启用
          //       </Radio.Button>
          //       <Radio.Button
          //         value="c"
          //         onClick={() => {
          //           setFilterServerStatus(false);
          //         }}
          //       >
          //         禁用
          //       </Radio.Button>
          //     </Radio.Group>
          //   </Space>,
          // );

          // toolbarDoms.push(
          //   <Space>
          //     <b>级别</b>
          //     <Radio.Group defaultValue="a" buttonStyle="solid">
          //       <Radio.Button
          //         value="a"
          //         onClick={() => {
          //           setFilterLevel(undefined);
          //         }}
          //       >
          //         全部
          //       </Radio.Button>
          //       <Radio.Button
          //         value={c.MemberLevel.Trial.value}
          //         onClick={() => {
          //           setFilterLevel(c.MemberLevel.Trial.value);
          //         }}
          //       >
          //         {c.MemberLevel.Trial.label}
          //       </Radio.Button>
          //       <Radio.Button
          //         value={c.MemberLevel.Free.value}
          //         onClick={() => {
          //           setFilterLevel(c.MemberLevel.Free.value);
          //         }}
          //       >
          //         {c.MemberLevel.Free.label}
          //       </Radio.Button>
          //       <Radio.Button
          //         value={c.MemberLevel.VIP.value}
          //         onClick={() => {
          //           setFilterLevel(c.MemberLevel.VIP.value);
          //         }}
          //       >
          //         {c.MemberLevel.VIP.label}
          //       </Radio.Button>
          //       <Radio.Button
          //         value={c.MemberLevel.Internal.value}
          //         onClick={() => {
          //           setFilterLevel(c.MemberLevel.Internal.value);
          //         }}
          //       >
          //         {c.MemberLevel.Internal.label}
          //       </Radio.Button>
          //     </Radio.Group>
          //   </Space>,
          // );

          toolbarDoms.push(
            <Space>
              {/* <b>分组</b> */}
              <TreeSelect
                style={{ minWidth: '350px' }}
                listHeight={900}
                maxTagCount={1}
                dropdownMatchSelectWidth={false}
                placeholder="选择分组过滤"
                allowClear={true}
                showSearch={true}
                treeCheckable={true}
                // multiple={false}
                treeDefaultExpandAll
                treeData={groupTreeData}
                value={groupIds}
                treeNodeFilterProp="title"
                onChange={(value) => {
                  setGroupIds(value ? value : undefined);
                }}
                // filterTreeNode={(input, option) =>
                //   option && option.title ? option.title.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0 : false
                // }
              />
            </Space>,
          );

          toolbarDoms.push(
            <Space
              style={{
                marginRight: '10px',
              }}
            >
              <span>
              <UserOutlined /> <Tag color="blue">
                  <b>{utils.formatNumber(totalUserCount)}</b>
                </Tag>
              </span>
              <span>
              <CloudServerOutlined />  <Tag color="blue">
                  <b>
                    {utils.formatNumber(totalValidServerCount)} /{' '}
                    {utils.formatNumber(totalServerCount)}
                  </b>
                </Tag>
              </span>
            </Space>,
          );
          
          if (hasRight('deploy_create')) {
            toolbarDoms.push([
              <Button
                key="deploy_create"
                type="primary"
                onClick={() => {
                  setFormDeployVisible(true);
                  setSelectServer(undefined);
                }}
              >
                部署
              </Button>,
            ]);
          }

          // if (hasRight('vpnserver_delete')) {
          //   toolbarDoms.push([

          //   // <Popconfirm
          //   //   key="delete"
          //   //   title="确定要删除吗?"
          //   //   onConfirm={async () => {
          //   //     // await handleRemove(record.id);
          //   //   }}
          //   // >
          //     <Button
          //       type="primary"
          //       key="deleteBatchInst"
          //       onClick={() => {
          //         setFormBatchRemoveVisible(true);
          //       }}
          //     >
          //       <DeleteOutlined />批量
          //     </Button>
          //     // </Popconfirm>,
          //   ]);
          // }
          
          // if (hasRight('vpnserver_create')) {
          //   toolbarDoms.push([
          //     <Button
          //       type="primary"
          //       key="buyVpnserver"
          //       onClick={() => {
          //         setFormBuyVisible(true);
          //       }}
          //     >
          //       <PlusOutlined />
          //       购买
          //     </Button>,
          //   ]);
          // }

          if (hasRight('vpnserver_create')) {
            toolbarDoms.push([
              // <Button
              //   type="primary"
              //   key="updateAwsIps"
              //   onClick={() => {
              //     setFormBatchAwsIpVisible(true);
              //   }}
              // >
              //   改IP
              // </Button>,
              <Popconfirm
                key="syncIps"
                title="确定要开始同步IP吗?"
                onConfirm={async () => {
                  setFormSyncIpVisible(true);
                }}
              >
                <Button type="primary">同步IP</Button>
              </Popconfirm>,
              <Button
                type="primary"
                key="createBatch"
                onClick={() => {
                  setFormBatchVisible(true);
                }}
              >
                <PlusOutlined />
                批量
              </Button>,
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined />
                新建
              </Button>,
              <Button
                key="export_ip"
                type="primary"
                onClick={() => {
                  setFormExportIpVisible(true);
                }}
              >
                导IP
              </Button>,
              <Button
                key="export_yaml"
                type="primary"
                onClick={() => {
                  setFormExportYamlVisible(true);
                }}
              >
                导YML
              </Button>,
            ]);
          }

          
          
          if (hasRight('vpnserver_update')) {
            toolbarDoms.push([
                
            <TableDropdown
              key="actionServerMonitor"
              menus={[
                {
                  key: 'publish_config',
                  name: (
                    <span>
                    <Button
                      key="btn_publish_config"
                      type="primary"
                      onClick={async() => {
                        await handlePublishConfig(true, false);
                      }}
                    >
                    下发修改配置
                    </Button>
                    </span>
                  ),
                },
                {
                  key: 'publish_config_select',
                  name: (
                    <span>
                    <Button
                      key="btn_publish_config_select"
                      type="primary"
                      onClick={async() => {
                        await handlePublishConfig(false, true);
                      }}
                    >
                    下发选中配置
                    </Button>
                    </span>
                  ),
                },
                // {
                //   key: 'publish_config_must',
                //   name: (
                //     <span>
                //     <Button
                //       key="btn_publish_config_must"
                //       type="primary"
                //       danger
                //       onClick={async() => {
                //         await handlePublishConfig(true, true);
                //       }}
                //     >
                //     强制下发配置
                //     </Button>
                //     </span>
                //   ),
                // },
              ]}
            >
              <Button type="primary">
                下发配置 ...
              </Button>
            </TableDropdown>,
            

            ]);
          }

          
          return toolbarDoms;
        }}
        columns={columns}
        params={{
          productId:
            productId && productId !== c.DefaultOptionAll.key
              ? parseInt(productId)
              : undefined,
          groupIds: groupIds,
        }}
        request={loadData}
        rowSelection={{
          defaultSelectedRowKeys: [],
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectIds(selectedRowKeys);
          },
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>

            <span>
              {hasRight('vpnserver_delete') ? (
                <Popconfirm
                  key="removeSererList"
                  title="确定要批量删除服务器？"
                  onConfirm={async () => {
                    handleRemoveList();
                  }}
                >
                  <a onClick={async () => {}}>删除</a>
                </Popconfirm>
              ) : (
                ''
              )}
            </span>

            {hasRight('deploy_create') ? (
              <span>
                <a
                  onClick={async () => {
                    setFormDeployVisible(true);
                    setSelectServer(selectedRows);
                  }}
                >
                  部署服务器
                </a>
              </span>
            ) : (
              ''
            )}

            <span>
              {hasRight('deploy_create') ? (
                <Popconfirm
                  key="recover_host"
                  title="确定要恢复部署HOST信息？"
                  onConfirm={async () => {
                    handleRecover();
                  }}
                >
                  <a onClick={async () => {}}>恢复部署HOST信息</a>
                </Popconfirm>
              ) : (
                ''
              )}
            </span>


            <span>
              {hasRight('vpnserver_update') ? (
                <a
                  onClick={async () => {
                    setFormBatchChangeVisible(true);
                  }}
                >
                  批量修改服务器信息
                </a>
              ) : (
                ''
              )}
            </span>
          </Space>
        )}
      />

      <VpnServerForm
        visible={formVisible}
        loadNodeId={current?.id}
        defaultGroupIds={groupIds && groupIds.length > 0 ? groupIds : undefined}
        // current={current}
        // onSubmit={handleFormSubmit}
        onSubmit={() =>{
          setDeployConfigPublish(true);
          setCurrent(undefined);
          setFormVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
      <VpnServerBatchForm
        visible={formBatchVisible}
        onSubmit={handleFormBatchSubmit}
        onCancel={() => {
          setFormBatchVisible(false);
        }}
      />
      <VpnServerBatchRemoveForm
        visible={formBatchRemoveVisible}
        onSubmit={handleFormBatchRemoveSubmit}
        onCancel={() => {
          setFormBatchRemoveVisible(false);
        }}
      />
      <VpnServerExportIpForm
        visible={formExportIpVisible}
        onCancel={() => {
          setFormExportIpVisible(false);
        }}
      />
      <VpnServerExportYamlForm
        visible={formExportYamlVisible}
        onCancel={() => {
          setFormExportYamlVisible(false);
        }}
      />
      <SyncIpForm
        visible={formSyncIpVisible}
        onCancel={() => {
          setDeployConfigPublish(true);
          actionRef.current?.clearSelected?.();
          setFormSyncIpVisible(false);          
          actionRef.current?.reload();          
        }}
      />
      <BatchChangeForm
        visible={formBatchChangeVisible}
        selectIds={selectIds}
        onSubmit={() => {
          setDeployConfigPublish(true);
          setFormBatchChangeVisible(false);
          actionRef.current?.clearSelected?.();
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setFormBatchChangeVisible(false);
        }}
      />
      <DeployForm
        visible={formDeployVisible}
        servers={selectServer}
        onSubmit={() => {
          setFormDeployVisible(false);
          actionRef.current?.clearSelected?.();
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setFormDeployVisible(false);
        }}
      />
      
    </PageContainer>
  );
};

export default VpnServerList;
